import axios from 'axios'; // 引入axios
import qs from 'qs'; // 引入qs
import Global from './global'; // 引入global.js
import Vue from 'vue';

crossLogin()

function crossLogin() { // 链接自动登录跳转

	let crosslogin = { // 登录参数
		username: '',
		password: '',
		access_token: ''
	}
	let canShu = {} // 存储链接携带的参数

	let routersPush = ['inspection'] // 存储要跳转的路由

	window.location.href.split('?')[1] && decodeURI(window.location.href).split('?')[1].split('&').map(i => {
		i.includes('username') && (crosslogin.username = i.split('=')[1])
		i.includes('password') && (crosslogin.password = i.split('=')[1])
		i.includes('access_token') && (crosslogin.access_token = i.split('=')[1])
		i.includes('data_json') && (canShu = JSON.parse(i.split('=')[1]))
	})

	var shouYe = window.location.href.split('?')[0] // 首页地址
	if (!crosslogin.username && !crosslogin.password && !crosslogin.access_token) return // 用户名、密码、access_token为空，不提交

	var url = process.env.NODE_ENV == 'development' ? '//172.16.13.146' + '/api/login/login' : 'api/login/login'
	axios.post(url, {
		usernum: crosslogin.username,
		userpassword: crosslogin.password,
		access_token: crosslogin.access_token
	}).then(response => {
		// console.log(response, 66666666666667)
		if (response.data.code == 200) {
			sessionStorage.setItem('token', response.data.data.token)
			localStorage.setItem('logintoken', response.data.data.token)
			sessionStorage.setItem('canShu', JSON.stringify(canShu))
			// 登录成功，获取跳转权限
			axios.get('/api/login/checkthisnode', {
				params: {
					url: canShu.module,
					token: response.data.data.token,
					checkschoolappcode: ''
				}
			}).then(respon => {

				if (respon.data.result == 200) {

					axios.get('api/setting/browser_set').then(res => {
						sessionStorage.setItem('siteTitle', res.data.data.data.name)
					})

					// 有权限，则获取用户信息
					axios.get(url).then(resp => {

						sessionStorage.setItem('user_info_str', JSON.stringify(resp.data.data.data.userinfo))
						sessionStorage.setItem('CheckSchoolAppCode', resp.data.data.data.userinfo.app_code)

						// if(routersPush.some(item=> item == canShu.module)) {
						// 如果要求跳转的路由里有这一项就跳转该路由
						if (canShu.module == 'inspection') {
							window.location.replace(canShu.module)
						} else {
							window.location.replace(canShu.decision_platform + '/' + canShu.module)
						}
						// }else{
						// 否则跳转首页
						// window.location.replace(shouYe)
						// }

					}).catch(error => {
						console.log(error, '获取用户信息异常')
						Vue.prototype.$message.error("获取用户信息异常")
					})

				} else {
					// 无权限则跳转首页
					Vue.prototype.$message.error('无该应用使用权限')
					window.location.replace(shouYe)
				}
			}).catch(error => {
				console.log(error, '获取访问权限异常')
				Vue.prototype.$message.error("获取访问权限异常")
			})
		} else {
			// 账号、密码错误，跳转首页
			Vue.prototype.$message.error(response.data.msg)
			window.location.replace(shouYe)
		}

	}).catch(error => {
		console.log(error, '登录异常')
	})
}

// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 60000; // 设置超时值1分钟
// axios.defaults.responseType  = 'json'         // 默认数据响应类型
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.withCredentials = false; // 表示跨域请求时是否需要使用凭证
//登录标识位置
var loginInx = location.href.indexOf('/login?');
//截取参数 , 截取问号后面的字符串
var queryString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1).split('?');
var queryArr = is_empty(queryString[1]) ? '' : queryString[1].split('&');
var queryObj = {};
//参数组合对象
for (var i = queryArr.length - 1; i >= 0; i--) {
	var temp = queryArr[i].split('=');
	queryObj[temp[0]] = temp[1];
}
if (loginInx > -1) {
	//登录token是否空
	if (is_empty(queryObj.token)) {
		queryObj.token = '--';
	}
	sessionStorage.setItem('token', queryObj.token);
	localStorage.setItem('logintoken', queryObj.token)
	delete queryObj.token;
}
var redirectUrl = '/login?token=' + queryObj.token;
//请求服务器host字段为空,则使用当前地址的host
if (!is_empty(queryObj.host)) {
	sessionStorage.setItem('host', queryObj.host);
	redirectUrl += '&host=' + queryObj.host;
	delete queryObj.host;
} else if (is_empty(sessionStorage.getItem('host'))) {
	sessionStorage.setItem('host', location.host);
	redirectUrl += '&host=' + location.host;
}
//设置websocket请求地址
var ip = sessionStorage.getItem('host').split(":");
sessionStorage.setItem('user_chat_url', 'ws://' + ip[0] + ':7272')
//请求服务器procotol字段为空,则使用当前地址的procotol
if (!is_empty(queryObj.protocol)) {
	sessionStorage.setItem('protocol', queryObj.protocol);
	redirectUrl += '&protocol=' + queryObj.protocol;
	delete queryObj.protocol;
} else if (is_empty(sessionStorage.getItem('protocol'))) {
	sessionStorage.setItem('protocol', location.protocol.replace(':', ''));
	redirectUrl += '&procotol=' + location.protocol.replace(':', '');
}
//设置跳转其他内部平台的地址 例如 后台,个人中心
sessionStorage.setItem('redirect_params', '/login?token=' + localStorage.getItem('logintoken'));
//设置请求地址
sessionStorage.setItem('host_addr', sessionStorage.getItem('protocol') + '://' + sessionStorage.getItem('host'));

if (!is_empty(queryObj.ItcJwtToken)) {
	sessionStorage.setItem('ItcJwtToken', queryObj.ItcJwtToken);
	delete queryObj.ItcJwtToken;
}
if (!is_empty(queryObj.CheckSchoolAppCode)) {
	sessionStorage.setItem('CheckSchoolAppCode', queryObj.CheckSchoolAppCode);
	delete queryObj.CheckSchoolAppCode;
}

/** 
		PS 登录时必须要携带的参数 token 在登录时有效的参数 CheckSchoolAppCode ItcJwtToken
			 其他参数作为跳转到相应模块的参数用paramString来存储,约定 routerUrl 为跳转的路由
*/
var paramString = '';
//模块字符串
var moduleString = '';
var urlString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1);
var endInx = urlString.indexOf('?');
if (endInx === -1) {
	var urlStringObj = [urlString];
} else {
	var urlStringObj = urlString.substring(0, endInx).split('/');
}
if (is_empty(urlStringObj[0])) {
	moduleString = 'home';
	paramString = '/' + moduleString;
} else if (urlStringObj[0] == 'login') {
	if (is_empty(queryObj.routerUrl)) {
		moduleString = 'home';
		paramString = '/' + moduleString;
	} else {
		moduleString = queryObj.routerUrl.split('/')[0];
		paramString = queryObj.routerUrl;
	}
} else {
	moduleString = urlStringObj[0];
	paramString = '/' + moduleString;
}
sessionStorage.setItem('decisionPlatform', moduleString);
//剩下的参数作为跳转的参数
paramString += Object.keys(queryObj).length === 0 ? '' : '?';
let inx = 0;
delete queryObj.routerUrl;
Object.keys(queryObj).forEach(function (key) {
	paramString += (inx === 0 ? '' : '&') + key + '=' + queryObj[key];
	inx++;
})
sessionStorage.setItem('paramString', paramString);
Global.decisionPlatform = sessionStorage.getItem('decisionPlatform');

axios.defaults.baseURL = sessionStorage.getItem('host_addr')
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
var company = 'BL';
var device_name = 'TE-0600R';

// token 过期，取消多条数据请求，放在多个错误弹窗
const CancelToken = axios.CancelToken;
console.log('config')
axios.interceptors.request.use(
	config => {

		config.cancelToken = new CancelToken(function executor(c) {
			Global.isCancelSource = c;
		})

		if (localStorage.getItem('access_token')) {
			config.headers.Authorization = `Bearer ${Global.access_token}`;
			config.headers.DecisionPlatform = sessionStorage.getItem('decisionPlatform');
			config.headers.token = localStorage.getItem('logintoken') == '--' ? null : localStorage.getItem('logintoken');
			config.headers.ItcJwtToken = sessionStorage.getItem('ItcJwtToken');
			config.headers.CheckSchoolAppCode = sessionStorage.getItem('CheckSchoolAppCode')
			var actioncodeArr = config.url.split('/');
			if (config.method == 'post' || config.method == 'put') {
				if (!config.data.hasOwnProperty('company')) {
					if (config.headers['content-type'] != 'multipart/form-data') {
						var requestData = config.data;
						delete config.data;
						config.data = {};
						config.data.company = company;
						config.data.device_name = device_name;
						config.data.sign = `${Global.access_token}`;
						config.data.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
						config.data.data = requestData;
						config.data = qs.stringify(config.data);
					}
				}

			} else if (config.method == 'get' || config.method == 'delete') {
				if (config.params === undefined) {
					config.params = {};
				}
				if (!config.params.hasOwnProperty('company')) {
					var requestData = config.params;
					delete config.params;
					config.params = {};
					config.params.company = company;
					config.params.device_name = device_name;
					config.params.sign = `${Global.access_token}`;
					config.params.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
					config.params.data = requestData;
				}
			}

		}
		return config;
	},
	err => {
		return Promise.reject(err);
	}
);

// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(
	response => {
		if (response.data.result === 400404) {
			Vue.prototype.$message.error("已过期，请登录")
			let host_addr = sessionStorage.getItem('host_addr');
			setTimeout(() => {
				localStorage.clear();
				sessionStorage.clear();
				window.location.href = host_addr;
			}, 1500)
		}
		// 对响应数据做点什么
		if (!response.config.hasOwnProperty('func')) {
			response.config.func = {};
		}
		var responseData
		if (response.data.hasOwnProperty('data')) {
			responseData = handleResponseData(response.data, 'need');
		} else {
			responseData = response.data;
		}

		// 对响应数据做点什么
		Vue.prototype.Ajax_callback(responseData, response.config.func)
		return response;
	}, error => {
		//超时响应
		if (error.message.indexOf('timeout') > -1) {
			Vue.prototype.Ajax_callback({
				status: 'timeout',
				msg: '请求超时'
			}, error.config.func);
			return false;
		}
		// 对响应错误做点什么
		else if (error.response.status == 401) {
			var config = error.config;
			get_access_token(function () {
				//重新发送请求，并执行回调

				if (config.method == 'post' || config.method == 'put') {
					//qs.stringify反向转换成对象

					config.data = qs.parse(config.data);
				}
				if (!config.hasOwnProperty('func')) {
					config.func = {};

				}
				//执行之前的ajax请求
				axios(config).then(response => Vue.prototype.Ajax_callback(response.data, config.func));
			});

		} else if (error.response.status == 505) {
			//2后跳回首页
			Vue.prototype.$message.error("已过期，请登录")
			let host_addr = sessionStorage.getItem('host_addr');
			setTimeout(() => {
				sessionStorage.clear();
				window.location.href = host_addr;
			}, 1500)
		} else if (error.response.status == 506) {
			//506说明ItcJwtToken已更改
			// console.log(getCookie(itc_jwt_token))
			let ItcJwtToken = getCookie(itc_jwt_token);
			sessionStorage.setItem('ItcJwtToken', ItcJwtToken);
			setTimeout(() => {
				window.location.reload();
			}, 1500)
		} else if (error.response.status == 606) {
			window.location.href = location.protocol + '//' + location.host + '/home/cdkey';
		} else {
			// 对响应数据做点什么
			if (!error.response.config.hasOwnProperty('func')) {

				error.response.config.func = {};
			}
			console.log('error', error.response.config)
			Vue.prototype.Ajax_callback(error.response.data, error.response.config.func)
		}
		return Promise.reject(error);
	});

export default axios; // 这句千万不能漏下！！！

/**
 * 获取access_token 方法封装
 */
function get_access_token(callback) {
	axios.get('/accessToken', {
		params: {
			company: 'BL',
			device_name: 'TE-0600R',
			data: {
				client_id: Global.client_id,
				secret: Global.secret
			}
		}
	})
		.then(response => {
			let data = response.data.data;
			Global.access_token = data.access_token;
			localStorage.setItem('access_token', Global.access_token);
			callback();
		});
}

/**
 * 获取cookie里某个键的值
 */
function getCookie(name) {
	var strcookie = document.cookie; //获取cookie字符串
	var arrcookie = strcookie.split("; "); //分割
	//遍历匹配
	for (var i = 0; i < arrcookie.length; i++) {
		var arr = arrcookie[i].split("=");
		if (arr[0] == name) {
			return arr[1];
		}
	}
	return "";
}